package com.evan.review.architecture.mvvm.view;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.evan.review.R;
import com.evan.review.architecture.mvvm.model.Note;
import com.evan.review.architecture.mvvm.view.adapter.NoteAdapter;
import com.evan.review.architecture.mvvm.viewmodel.NoteViewModel;
import com.google.android.material.chip.Chip;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;
import java.util.List;

/**
 * MVVM架构示例Activity
 * 作为View层，负责UI展示和用户交互
 * 通过ViewModel与数据层通信
 */
public class MVVMExampleActivity extends AppCompatActivity {
    
    public static final int ADD_NOTE_REQUEST = 1;
    public static final int EDIT_NOTE_REQUEST = 2;
    
    private NoteViewModel noteViewModel;
    private RecyclerView recyclerView;
    private NoteAdapter adapter;
    private TextView textViewEmpty;
    private ProgressBar progressBar;
    private EditText editTextSearch;
    private Button buttonSearch;
    private Chip chipAll, chipAndroid, chipArchitecture, chipTutorial, chipHighPriority, chipArchived;
    private FloatingActionButton fabAddNote;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvvm_example);
        
        // 初始化视图
        initViews();
        
        // 设置RecyclerView
        setupRecyclerView();
        
        // 初始化ViewModel
        noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
        
        // 观察LiveData数据变化
        observeViewModel();
        
        // 设置点击事件
        setupClickListeners();
    }
    
    private void initViews() {
        recyclerView = findViewById(R.id.recycler_view);
        textViewEmpty = findViewById(R.id.text_view_empty);
        progressBar = findViewById(R.id.progress_bar);
        editTextSearch = findViewById(R.id.et_search);
        buttonSearch = findViewById(R.id.btn_search);
        fabAddNote = findViewById(R.id.fab_add_note);
        
        // 初始化Chips
        chipAll = findViewById(R.id.chip_all);
        chipAndroid = findViewById(R.id.chip_android);
        chipArchitecture = findViewById(R.id.chip_architecture);
        chipTutorial = findViewById(R.id.chip_tutorial);
        chipHighPriority = findViewById(R.id.chip_high_priority);
        chipArchived = findViewById(R.id.chip_archived);
    }
    
    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        
        adapter = new NoteAdapter();
        recyclerView.setAdapter(adapter);
        
        // 设置滑动删除
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
                ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder,
                                  @NonNull RecyclerView.ViewHolder target) {
                return false;
            }
            
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                Note deletedNote = adapter.getNoteAt(viewHolder.getAdapterPosition());
                noteViewModel.delete(deletedNote);
                
                Snackbar.make(findViewById(android.R.id.content), "笔记已删除", Snackbar.LENGTH_LONG)
                        .setAction("撤销", v -> noteViewModel.insert(deletedNote))
                        .show();
            }
        }).attachToRecyclerView(recyclerView);
        
        // 设置点击事件
        adapter.setOnItemClickListener(note -> {
            Intent intent = new Intent(MVVMExampleActivity.this, AddEditNoteActivity.class);
            intent.putExtra(AddEditNoteActivity.EXTRA_ID, note.getId());
            intent.putExtra(AddEditNoteActivity.EXTRA_TITLE, note.getTitle());
            intent.putExtra(AddEditNoteActivity.EXTRA_CONTENT, note.getContent());
            intent.putExtra(AddEditNoteActivity.EXTRA_CATEGORY, note.getCategory());
            intent.putExtra(AddEditNoteActivity.EXTRA_PRIORITY, note.getPriority());
            startActivityForResult(intent, EDIT_NOTE_REQUEST);
        });
    }
    
    private void observeViewModel() {
        // 默认观察所有笔记
        noteViewModel.getAllNotes().observe(this, notes -> {
            updateUI(notes);
        });
    }
    
    private void updateUI(List<Note> notes) {
        progressBar.setVisibility(View.GONE);
        
        if (notes.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            textViewEmpty.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            textViewEmpty.setVisibility(View.GONE);
            adapter.submitList(notes);
        }
    }
    
    private void setupClickListeners() {
        // 添加笔记按钮点击事件
        fabAddNote.setOnClickListener(v -> {
            Intent intent = new Intent(MVVMExampleActivity.this, AddEditNoteActivity.class);
            startActivityForResult(intent, ADD_NOTE_REQUEST);
        });
        
        // 搜索按钮点击事件
        buttonSearch.setOnClickListener(v -> {
            String query = editTextSearch.getText().toString().trim();
            if (!query.isEmpty()) {
                progressBar.setVisibility(View.VISIBLE);
                noteViewModel.setSearchQuery(query);
                noteViewModel.getSearchResults().observe(this, this::updateUI);
            }
        });
        
        // 分类筛选点击事件
        chipAll.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            noteViewModel.getAllNotes().observe(this, this::updateUI);
        });
        
        chipAndroid.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            noteViewModel.setCategoryFilter("Android");
            noteViewModel.getNotesByCategory().observe(this, this::updateUI);
        });
        
        chipArchitecture.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            noteViewModel.setCategoryFilter("架构");
            noteViewModel.getNotesByCategory().observe(this, this::updateUI);
        });
        
        chipTutorial.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            noteViewModel.setCategoryFilter("教程");
            noteViewModel.getNotesByCategory().observe(this, this::updateUI);
        });
        
        chipHighPriority.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            noteViewModel.getHighPriorityNotes().observe(this, this::updateUI);
        });
        
        chipArchived.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            noteViewModel.getArchivedNotes().observe(this, this::updateUI);
        });
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (data == null) {
            return;
        }
        
        if (requestCode == ADD_NOTE_REQUEST && resultCode == RESULT_OK) {
            String title = data.getStringExtra(AddEditNoteActivity.EXTRA_TITLE);
            String content = data.getStringExtra(AddEditNoteActivity.EXTRA_CONTENT);
            String category = data.getStringExtra(AddEditNoteActivity.EXTRA_CATEGORY);
            int priority = data.getIntExtra(AddEditNoteActivity.EXTRA_PRIORITY, 3);
            
            Note note = new Note(title, content, category, priority);
            noteViewModel.insert(note);
            
            Toast.makeText(this, "笔记已保存", Toast.LENGTH_SHORT).show();
        } else if (requestCode == EDIT_NOTE_REQUEST && resultCode == RESULT_OK) {
            int id = data.getIntExtra(AddEditNoteActivity.EXTRA_ID, -1);
            
            if (id == -1) {
                Toast.makeText(this, "笔记无法更新", Toast.LENGTH_SHORT).show();
                return;
            }
            
            String title = data.getStringExtra(AddEditNoteActivity.EXTRA_TITLE);
            String content = data.getStringExtra(AddEditNoteActivity.EXTRA_CONTENT);
            String category = data.getStringExtra(AddEditNoteActivity.EXTRA_CATEGORY);
            int priority = data.getIntExtra(AddEditNoteActivity.EXTRA_PRIORITY, 3);
            
            Note note = new Note(title, content, category, priority);
            note.setId(id);
            noteViewModel.update(note);
            
            Toast.makeText(this, "笔记已更新", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_mvvm, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.delete_all_notes) {
            showDeleteAllNotesDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void showDeleteAllNotesDialog() {
        new AlertDialog.Builder(this)
                .setTitle("删除所有笔记")
                .setMessage("确定要删除所有笔记吗？此操作不可撤销。")
                .setPositiveButton("删除", (dialog, which) -> {
                    noteViewModel.deleteAllNotes();
                    Toast.makeText(this, "所有笔记已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 